// src/services/scheduler.service.js
const schedule = require('node-schedule');
const prisma = require('../config/database');
const emailService = require('./email.service');
const notificationService = require('./notification.service');
const { getSocketId } = require('../utils/zym-socketIoUtils');
const backupService = require('./backupService');
const destroyService = require('./destroy.service');

// 避免循环依赖，在使用时再获取
let io = null;
let userList = null;

// 在需要使用时初始化io和userList
function getIoAndUserList() {
  if (!io || !userList) {
    try {
      const mainModule = require('../index');
      io = mainModule.io;
      userList = mainModule.userList;
    } catch (err) {
      console.error('获取io或userList失败:', err);
    }
  }
  return { io, userList };
}

// 获取当前东八区时间
const getCurrentUTC8Time = () => {
  const now = new Date();
  return new Date(now.getTime() + (8 * 60 * 60 * 1000));
};

// 转换时间到东八区（UTC+8）
const convertToUTC8 = (date) => {
  if (!date) return null;
  return new Date(date.getTime() + (8 * 60 * 60 * 1000));
};

// 初始化定时任务
exports.initScheduler = () => {
  // 每3小时检查一次任务提醒(例如：0点、3点、6点、9点...)
  // schedule.scheduleJob('0 */3 * * *', async () => {
  //   console.log('执行批阅任务提醒检查...');
  //   await checkReviewAssignments();
  // });

   // 每隔3小时检查一次任务提醒   */5 * * * * *    */2 * * * *
   schedule.scheduleJob('0 0 */3 * * *', async () => {
    console.log('执行批阅任务提醒检查...');
    await checkReviewAssignments();
  });

  // 每天凌晨2点执行增量备份    0 2 * * *
  schedule.scheduleJob('0 2 * * *', async function() {
    console.log('执行夜间增量备份...');
    await backupService.incrementalBackup();
  });
  
  // 每周日凌晨3点执行全量备份  */5 * * * * *   0 3 * * 0
  schedule.scheduleJob('*/5 * * * * *', async function() {
    console.log('执行周末全量备份...');
    await backupService.fullBackup();
  });
  
  // 每月1日凌晨4点执行清理过期备份
  schedule.scheduleJob('0 4 1 * *', async function() {
    console.log('清理过期备份...');
    await backupService.cleanOldBackups(60); // 保留60天内的备份
  });

    // 添加新的定时任务：每年的1月1日凌晨1点执行旧考试数据销毁
    schedule.scheduleJob('0 1 1 1 *', async function() {
      console.log('执行年度考试数据销毁...');
      // 计算一年前的日期
      const cutoffMoment = moment.tz('Asia/Shanghai').subtract(1, 'year');
      const cutoffDate = cutoffMoment.format('YYYY-MM-DD HH:mm:ss');

      // 销毁一年前的考试数据
      const result = await destroyService.destroyOldExaminations(cutoffDate);
      console.log('销毁结果:', result);
    });
 
 
  
  console.log('批阅任务提醒调度器已启动');
};

// 检查批阅任务并发送提醒
async function checkReviewAssignments() {
  try {
    const now = getCurrentUTC8Time();
    const tomorrow = new Date(now);
    tomorrow.setHours(tomorrow.getHours() + 24); // 24小时内到期的任务
    
    // 获取即将到期但未完成的批阅任务
    const assignments = await prisma.review_assignment.findMany({
      where: {
        status: { in: [1, 2] }, // 1-待批阅 2-批阅中
        end_time: {
          gt: now,
          lt: tomorrow
        }
      }
    });
    
    console.log(`找到 ${assignments.length} 个即将到期的批阅任务`);
    
    for (const assignment of assignments) {
      // 计算完成情况
      const completionInfo = await getCompletionInfo(assignment);
      const endTimeUTC8 = new Date(assignment.end_time);
      const hoursLeft = Math.round((endTimeUTC8 - now) / (1000 * 60 * 60));
      
      // 如果完成度低于90%，发送提醒
      if (completionInfo.completionRate < 0.9 && hoursLeft <= 24) {
        
    
        
        
        // 创建站内通知(系统通知表)
        await notificationService.createReviewReminderNotification(
          assignment.user_id,
          assignment.id
        );
        
        // 获取io和userList实例，然后检查教师是否在线
        const { io: socketIO, userList: users } = getIoAndUserList();
        
        if (socketIO && users) {
          // 检查教师是否在线，如果在线则通过socket发送实时提醒
          const teacherSocketIds = getSocketId(users, parseInt(assignment.user_id));
          if (teacherSocketIds && teacherSocketIds.length > 0) {
            // 获取考试信息
            const examination = await prisma.examination.findUnique({
              where: { id: assignment.examination_id }
            });
            
            // 构建通知内容
            const notificationData = {
              assignmentId: assignment.id,
              examinationName: examination ? examination.name : '未知考试',
              hoursLeft: hoursLeft,
              completionRate: Math.round(completionInfo.completionRate * 100),
              endTime: formatTimeToReadable(endTimeUTC8)
            };
            
            // 通过socket向教师发送实时通知
            teacherSocketIds.forEach(socketId => {
              socketIO.to(socketId).emit('assignmentRemind', {message:`考试:${notificationData.examinationName}的批阅任务将在${notificationData.hoursLeft}小时后到期，完成度:${notificationData.completionRate}%`});
            });
          } 
        } 
        
        // 如果任务完成度低于70%且剩余时间少于12小时，额外发送邮件提醒
        if (completionInfo.completionRate < 0.7 && hoursLeft <= 12) {
          await emailService.sendReviewReminderEmail(
            assignment.user_id,
            assignment.id
          );
          
         
        }
      }
    }
  } catch (error) {
    console.error('检查批阅任务失败:', error);
  }
}

// 将时间格式化为更易读的格式
function formatTimeToReadable(date) {
  if (!date) return '';
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 计算批阅任务完成情况
async function getCompletionInfo(reviewAssignment) {
  try {
    let totalCount = 0;
    let completedCount = 0;

    if (reviewAssignment.assignment_strategy === 1) {
      // 策略1: 按试卷分配
      // 获取分配的试卷数量
      const assignmentDetails = await prisma.review_assignment_detail.findMany({
        where: { 
          review_assignment_id: reviewAssignment.id,
          student_paper_id: { not: null }
        },
        select: {
          student_paper_id: true
        }
      });

      // 统计唯一的试卷ID
      const uniquePaperIds = [...new Set(assignmentDetails.map(d => d.student_paper_id))];
      totalCount = uniquePaperIds.length;

      // 统计已完成的试卷数量
      completedCount = await prisma.student_paper.count({
        where: {
          id: { in: uniquePaperIds },
          examination_status: 2  // 批阅完成状态
        }
      });
    } else if (reviewAssignment.assignment_strategy === 2) {
      // 策略2: 按题目分配
      // 统计分配的题目总数
      totalCount = await prisma.review_assignment_detail.count({
        where: { 
          review_assignment_id: reviewAssignment.id,
          paper_detail_id: { not: null }
        }
      });
      
      // 统计已完成的题目数量
      completedCount = await prisma.review_assignment_detail.count({
        where: { 
          review_assignment_id: reviewAssignment.id,
          paper_detail_id: { not: null },
          status: 1  // 已完成批阅
        }
      });
    }

    const completionRate = totalCount > 0 ? completedCount / totalCount : 0;

    return {
      totalCount,
      completedCount,
      completionRate
    };
  } catch (error) {
    console.error('计算批阅完成情况失败:', error);
    return { totalCount: 0, completedCount: 0, completionRate: 0 };
  }
}